<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //创建对象的第0种方式 字面量创建
        var carx2 = {
            color: "red",
            price: 10,
            brand: "bmw",
            drive: function () {
                console.log(carx2['color'])
                console.log("carx2 drive");
            }
        };
        carx2.drive();
        //obj["key"]也可以访问到属性的值
        console.log(carx2['price']);

        // 1.构造函数法 创建出来的每个对象都有独立的属性和方法 互不共享
        function createObj(name, age) {
            this.name = name;
            this.age = age;
        }
        var obj1 = new createObj('lin', 23)
        console.log(obj1);

        // 2.工厂方式 使用new 关键字已经深入人心，因此我们使用上面的方法去定义总感觉别扭，并且每次调用时都去创建新的属性以及函数，功能上也不实际。
        function createCar() {
            var Car = new Object();
            Car.color = 'red';
            Car.price = 998;
            Car.driver = [];
            Car.run = function () {
                console.log('car run');
            }
            return Car;
        }
        var car1 = createCar();
        var car2 = createCar();
        car2.color = 'yellow';
        car2.driver.push('lin');
        console.log(car1, car2);

        //工厂方式简写
        var carx = new Object();
        carx.size = "200";
        carx.name = "benz";
        carx.run = function () {
            console.log('car run');
        }
        carx.run();

        //3.原型方式
        // 先定义构造函数
        function Car() {};
        Car.prototype.color = 'blue';
        Car.prototype.driver = new Array('lin', 'hong');
        Car.prototype.showDriver = function () {
            this.driver.forEach(element => {
                console.log(element);
            });
        };
        // 这里不能带任何初始化参数 也是个缺点
        var c3 = new Car();
        var c4 = new Car();
        c3.driver.push('girl');
        c3.color = 'yellow';
        // c3改变了数组内容之后，c4也跟着改变了 这是不对的
        console.log('c3', c3, 'c4', c4);

        // 3.原型方式的另一种写法
        function Car2() {};
        Car2.prototype = {
            color: 'yellow',
            driver: ['huang'],
            showDriver() {
                this.driver.forEach((ele, index, arr) => {
                    console.log(ele, index, arr.length);
                })
            }
        }
        console.log('car2', new Car2());
    </script>
</body>

</html>